<template>
    <van-popup v-model="showFlag">
        <div class="img-wrapper" v-show="imgDone">
            <img src alt class="resultImg" />
        </div>

        <div class="share-page" ref="share" v-show="!imgDone">
            <div class="share-header">
                <img :src="avatarBase64" alt class="avatar" crossorigin="anonymous" />
                <span>{{ nickname }}的店</span>
            </div>
            <div class="share-main">
                <img :src="picBase64" alt class="product-img" @load="imgLoad" />
            </div>
            <div class="share-footer">
                <div class="share-footer-left">
                    <img :src="qrcodeWechat" style="width: 120px;height:120px" v-if="interState" />
                    <qrcode :text="qrcode" :size="120" error-level="M" v-else></qrcode>
                </div>
                <div class="share-footer-right">
                    <span class="product-desc">{{ formatProductName }}</span>
                    <span class="product-price-origin">原价:{{ product.money }}</span>
                    <span class="product-price-now">
                        {{
                        product.price | moneyFmt(2, '￥')
                        }}
                    </span>
                </div>
            </div>
            <div class="share-alert">长按保存图片至相册</div>
            <!--<svg class="close-icon" aria-hidden="true" @click.stop="hide"><use xlink:href="#icon-close"></use></svg>-->
        </div>
    </van-popup>
</template>
<script>
    import html2canvas from "html2canvas";
    import { protocol } from "@/config";
    import { commonMixin, productMixin, sysMixin } from "@/common/mixin";
    import API from "@/request/api";
    import wx from "weixin-js-sdk";
    // import {isIOS} from '@/common/utils';

    export default {
        mixins: [productMixin, commonMixin, sysMixin],
        data() {
            return {
                imgDone: false,
                showFlag: false,
                avatarBase64: "",
                picBase64: "",
                recordCount: 0,
                lastGid: "",
                val: "",
                qrcodeWechat: "",
                interState: false // 是否小程序环境,默认web环境
            };
        },
        props: {
            product: {
                type: Object,
                default: () => {}
            },
            sid: {
                type: String,
                default: ""
            },
            type: {
                type: String,
                default: "online"
            }
        },
        created() {
            if (window.__wxjs_environment === "miniprogram") {
                //    判断是否先程序环境
                this.interState = true;
                wx.miniProgram.postMessage({
                    data: {
                        system: this.system,
                        referid: this.uid,
                        name: this.product.name,
                        gid: this.product.gid,
                        page: "online-detail",
                        share: "1",
                        type: "online-detail"
                    }
                });
                // this.show();
            } else {
                // this.show();
            }
        },
        watch: {
            product() {
                this.request
                    .post(API.qrcode, {
                        scene: {
                            page: "online-detail",
                            gid: this.product.gid,
                            system: this.system,
                            referid: this.uid,
                            share: "1"
                        }
                    })
                    .then(res => {
                        console.log(res, "ressss");
                        this.qrcodeWechat = res.base64;
                    });
            }
        },
        computed: {
            qrcode() {
                return `${protocol}://${document.domain}/welcome?system=${
                    this.system
                }&referid=${this.uid}&page=online-detail&gid=${
                    this.product.gid
                }&share=1`;
            },
            uid() {
                return this.userInfo.uid ? this.userInfo.uid : "";
            },
            avatar() {
                return this.userInfo.avatar ? this.userInfo.avatar : "";
            },
            nickname() {
                if (!this.userInfo.nickname) {
                    return "";
                }
                return this.userInfo.nickname.length > 10
                    ? `${this.userInfo.nickname.substr(0, 10)}...`
                    : this.userInfo.nickname;
            },
            formatProductName() {
                if (!this.product.name) {
                    return "";
                }
                return this.product.name.length > 15
                    ? `${this.product.name.substr(0, 15)}...`
                    : this.product.name;
            },
            formatUserName() {
                if (!this.product.name) {
                    return "";
                }
                return this.product.name.length > 15
                    ? `${this.product.name.substr(0, 15)}...`
                    : this.product.name;
            }
        },
        // beforeRouteEnter(to, from, next) {
        //     // 修复iOS版微信h5 History兼容性问题
        //     if (isIOS() && to.path !== location.pathname) {
        //         location.assign(to.fullPath); // 此处不可使用location.replace
        //     } else {
        //         next();
        //     }
        // },
        methods: {
            imgLoad() {
                // console.log('loaded#############');
            },
            async show() {
                if (this.lastGid == this.product.gid) {
                    this.showFlag = true;
                    return;
                }
                this.imgDone = false;
                // console.log('start show share');
                if (this.product.name) {
                    //获取base64编码 解决移动端跨域问题
                    try {
                        // 写法一
                        let [avatarResult, productResult] = await Promise.all([
                            this._getBase64(this.avatar),
                            this._getBase64(this.product.pic)
                        ]);
                        this.avatarBase64 = this.formatBase64Src(
                            avatarResult.content
                        );
                        this.picBase64 = this.formatBase64Src(
                            productResult.content
                        );
                    } catch (e) {
                        // console.log(e);
                    }

                    this.showFlag = true;
                    this.$nextTick(() => {
                        this.domToImg();
                    }, 20);
                    this.lastGid = this.product.gid;
                }
            },
            hide() {
                this.showFlag = false;
            },
            domToImg() {
                let shareNode = this.$refs.share;
                const opts = {
                    scrollY: 0, // 纵向偏移量 写死0 可以避免滚动造成偶尔偏移的现象
                    useCORS: true // 【重要】开启跨域配置
                };
                setTimeout(() => {
                    html2canvas(shareNode, opts).then(_canvas => {
                        const img = document.querySelector(".resultImg");
                        img.src = _canvas.toDataURL();
                        this.imgDone = true;
                    });
                }, 20);
            },
            _getBase64(url) {
                if (!url) {
                    return "";
                }
                return this.request.get(API.picbase64, { url: url });
            },
            formatBase64Src(base64) {
                return `data:image/png;base64,${base64}`;
            }
        }
    };
</script>
<style lang="stylus" scoped>
    @import '~assets/main.styl';

    * {
        box-sizing: border-box;
    }

    .van-popup {
        overflow-y: hidden !important;
        background-color: rgba(0, 0, 0, 0) !important;
        transition: none 0s; // 很关键 去掉popup的过渡动画 因为这可能会影响html2canvas的渲染结果 引起偏移等现象
    }

    .img-wrapper {
        width: 300px;

        /* height 520px */
        .resultImg {
            width: 300px;
            /* height 520px */
        }
    }

    .share-page {
        background: #f9f9f9;
        width: 300px;
        height: 100%;
        /* padding 25px 25px */
        margin: 0 auto;

        .share-header {
            width: 250px;
            height: 50px;
            margin: 0 auto;
            text-align: left;
            font-size: word14;
            color: gray6;
            padding-top: 20px;

            .avatar {
                vertical-align: middle;
                width: 30px;
                height: 30px;
                border-radius: all-radius;
                margin-right: 13px;
            }
        }

        .share-main {
            width: 250px;
            height: 250px;
            margin: 10px auto;

            .product-img {
                width: 250px;
                height: 250px;
            }
        }

        .share-footer {
            position: relative;
            width: 250px;
            height: 130px;
            padding-top: 10px;
            margin: 0 auto;

            .share-footer-left {
                position: absolute;
                left: 0;
                width: 120px;
                height: 120px;

                .code-img {
                    width: 120px;
                    height: 120px;
                }
            }

            .share-footer-right {
                position: absolute;
                right: 0;
                width: 120px;
                height: 120px;
                text-align: left;
                margin-left: 10px;
                padding: vw(2) 0;
                flex-y(space-between, flex-start);

                .product-desc {
                    font-size: word14;
                    color: gray3;
                    display: block;
                    line-height: vw(18);
                }

                .product-price-now {
                    display: inline-block;
                    font-size: word20;
                    color: main-color;
                    line-height: vw(22);
                }

                .product-price-deduction {
                    display: inline-block;
                    font-size: word16;
                    color: main-color;
                    line-height: vw(19);
                }

                .product-price-origin {
                    display: inline-block;
                    font-size: word12;
                    color: gray9;
                    text-decoration: line-through;
                    line-height: vw(14);
                }
            }
        }

        .share-alert {
            margin: 20px auto;
            text-align: center;
            font-size: word14;
            color: #858585;
        }

        .close-icon {
            position: absolute;
            top: 25px;
            right: 25px;
            width: 10px;
            height: 10px;
            overflow: hidden;
            fill: gray9;
        }
    }

    .loading-container {
        position: absolute;
        top: 0;
        left: 0;
        z-index: 10;
        height: 100%;
        width: 100%;
        background-color: #f9f9f9;
        flex-y();
    }
</style>
